# Update by pmq 28-08-2010

import sys
from java.lang                                      import System
from com.l2jserver                                  import Config
from com.l2jserver.gameserver                       import ThreadPoolManager
from com.l2jserver.gameserver.datatables            import NpcTable
from com.l2jserver.gameserver.datatables            import SpawnTable
from com.l2jserver.gameserver.instancemanager       import FortManager
from com.l2jserver.gameserver.instancemanager       import InstanceManager
from com.l2jserver.gameserver.model.actor.instance  import L2PcInstance
from com.l2jserver.gameserver.model.entity          import Fort
from com.l2jserver.gameserver.model.entity          import Instance
from com.l2jserver.gameserver.model.quest           import State
from com.l2jserver.gameserver.model.quest           import QuestState
from com.l2jserver.gameserver.model.quest.jython    import QuestJython as JQuest
from com.l2jserver.gameserver.network               import SystemMessageId
from com.l2jserver.gameserver.network.serverpackets import SystemMessage
from com.l2jserver.gameserver.util                  import Util
from com.l2jserver.util                             import Rnd

qn = "512_AwlUnderFoot"

QuestId = 512
QuestName = "AwlUnderFoot"
QuestDesc = "Access Castle Dungeon"

#NPC
WARDEN = [ 36403, 36404, 36405, 36406, 36407, 36408, 36409, 36410, 36411 ]

#MONSTER TO KILL -- Only last 3 Raids (lvl ordered) from 162, drop DL_MARK
RAIDS1 = [ 25546, 25549, 25552 ]
RAIDS2 = [ 25553, 25554, 25557, 25560 ]
RAIDS3 = [ 25563, 25566, 25569 ]

#QUEST ITEMS
DL_MARK = 9798

#REWARDS
KNIGHT_EPALUETTE = 9912

#MESSAGES
warden_exchange = "<html><body>监狱管理员：<br>你已经处理掉地下监狱囚犯了吗？干得好！<br>谢谢您的帮助，解除了对我们的威胁。<br>这里是骑士的肩章的承诺。<br>你可以向宫廷魔法师交换城堡血盟补给品。<br>...<br>您想继续挑战吗？<br><br><a action=\"bypass -h Quest 512_AwlUnderFoot continue\">说想继续</a><br><a action=\"bypass -h Quest 512_AwlUnderFoot quit\">我要放弃</a></body></html>"
quest_no = "<html><body>监狱管理员：<br><center><font color=\"FF0000\">（功能尚未实装！）</font></center></body></html>"
warden_no = "<html><body>监狱管理员：<br>那您先准备一下，回来时，请来找我吧...</body></html>"
rumor = "<html><body>监狱管理员：<br>边缘菲拉卡虽然是梦的次元，但也会影响现实生活。像现在这样，越是浪费时间，困在菲拉卡的4名调查员越会处于危险。请您快点。<br><a action=\"bypass -h Quest 512_AwlUnderFoot quest_no\">请将我送到那个地方</a></body></html>"
warden_ask = "<html><body>监狱管理员：<br>哦...<br>因为长久岁月被放置的缘故，过去被囚禁的怪物-地下监狱的囚犯-们，目前各自形成势力。<br>在地下的监狱内，怪物们使用只有他们能够接近、移动的秘密通道，而这些秘密通道如蜘蛛网般的错综连接。<br>还听说这些通道也与地上怪物们掌控的地区连接在一起呢。<br>如此掌握要塞地下世界之主导权的势力组织，是由过去被囚禁的怪物们所组成的，而且还存在自定的阶级；听说城堡地下区域是由更高地位的魔物们掌握的，而要塞地下则由较低地位的魔物们占领。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_ask1\">之所以地下监狱内怪物们不断出没，就算再怎么征讨...</a></body></html>"
warden_ask1 = "<html><body>监狱管理员：<br>没错。<br>所以我们才会向血盟的冒险家们求助...<br>当然，听说高等职位的战略家与学者、魔法师们，正在寻求可永久性解决这问题的方法。<br>但是因为势力各异的城堡间之协力成了问题，所以进行的不太顺利。<br>总之，在解决方案出来之前，只好继续去征讨了。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_ask2\">我该做些什么呢？</a></body></html>"
warden_ask2 = "<html><body>监狱管理员：<br>过去在这地下监狱的魔物们和征讨部队之间，曾有过大规模的战斗。<br>真是场激烈的战斗...<br>双方都死伤惨重。<br>所以感到恐惧的魔物们也不敢轻易的将城地下监狱当成自家般的进出了。<br>不过近来城地下监狱内持续有流入曾是过去囚犯的强悍魔物，以三人组组成为一群的地下监狱族群。<br>虽不明缘由，但一定是在搞什么阴谋吧。<br>就麻烦冒险家您将<font color=\"LEVEL\">三人组</font>都击退后，击倒组成地下监狱囚犯族群的所有魔物吧。<br>将最后一组的首领怪物杀死后带回<font color=\"LEVEL\">城地下监狱魔物的阶级章碎片</font>的话，我就支付骑士肩章给您。<br>利用骑士肩章可以向宫廷魔法师交换城堡血盟补给品。<br>对了，还有...<br>到目前为止得到报告的地下监狱囚犯首领有<font color=\"LEVEL\">美貌的奈兹里耶、粗野的南庞、破坏者加斯</font>。<br>可透过我进入城地下监狱。<br>那就拜托您了。<br><a action=\"bypass -h Quest 512_AwlUnderFoot status\">询问城堡地下监狱情况</a></body></html>"
CastleWarden = "<html><body>监狱管理员：<br><br>这里是危险之地。若没有想要变得更强的意志，请别在这附近逗留。<br><br><a action=\"bypass -h Quest 512_AwlUnderFoot rumor\">我听到有关边缘菲拉卡的消息</a><br><a action=\"bypass -h Quest 512_AwlUnderFoot enter\">让我进入监狱吧</a><br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_quest.htm\">任务</a></body></html>"
default = "<html><body>监狱管理员：<br>目前没有执行任务，或条件不符。</body></html>"
nolvl = "<html><body>监狱管理员：<br>我很感谢冒险家您想要协助的心意，但我也是身为要塞的一员，可不希望让实力不符的血盟成员陷入险境。<br>如此之类的管理责任也是我的职务。<br>在接任这职务之前，我也曾是个叱吒风云的冒险家。<br以前辈的立场来看，冒险家您的实力还不足接任征讨任务。<br>去磨练实力后再来找我吧。<br>(只有等级70以上才可以执行的任务。)</body></html>"
noitem = "<html><body>监狱管理员：<br>你已经回来吗？<br1>你做不到了我的要求。你没有地下监狱魔物的阶级章碎片。</body></html>"
wrongcastle = "<html><body>监狱管理员：<br>(拥有此城堡的血盟之血盟成员才能执行的任务。)</body></html>"
noclan = "<html><body>监狱管理员：<br>你是谁？好像不在血盟成员的名单内...<br>(拥有此城堡的血盟之血盟成员才能执行的任务。)</body></html>"
finish = "<html><body>监狱管理员：<br>啊，我明白。果然，我没有看错人...<br>谢谢你为这里做的一切。<br>如果你想再次伸出援手的话，我们会非常感激。<br>祝你旅途愉快！</body></html>"
noparty = "<html><body>进入监狱的条件是，须组成2名以上的队伍，而且所有队伍成员必须有在进行任务才行。还有，开始训练后，至少在4小时之内无法增加额外的训练。</body></html>"
#noleader = "<html><body>监狱管理员：<br>为了在战斗中生存，最重要的是队伍的队长如何领导自己的队伍，当然，在菲拉卡内将领导您的人，也会是队长。所以，我非常尊重队伍的领导人物。您的队长是" + str(pln) + "，去将您的队长请来这边吧。<br>(只有队长才能试图进入。)</body></html>"
warden_quest = "<html><body>监狱管理员：<br>我是这个城堡的地下监狱管理员。这个地下监狱怪物阵营最近被发现的。<br>我知道其他城堡也有这样的地下监狱。我的责任是要保持这个地下监狱区安全。<br>毕竟，这将几乎是可取的怪物出现和消失在地牢的一座城堡，不是吗？<br>不幸的是，我们根本无法单独处理这个工作。<br>我们需要冒险家的帮助。<br>当然，我们会支付给您酬劳。<br><br><a action=\"bypass -h Quest 512_AwlUnderFoot start\">我会帮你的</a><br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_no\">我不是现在</a></body></html>"
warden_yes = "<html><body>监狱管理员：<br>进入城地下监狱后，将地下监狱囚犯击退吧。<br>冒险家您必须要将<font color=\"LEVEL\">三人组</font>都击退后，击倒组成地下监事囚犯族群的所有魔物才行。<br>将最后一组的首领怪物杀死后，带回城地下监狱魔物的阶级章碎片的话，我就支付骑士肩章给您。<br>利用骑士肩章可以向宫廷魔法师交换城堡血盟补给品。<br>对了，还有...<br>到目前为止得到报告的地下监狱囚犯首领有<font color=\"LEVEL\">美貌的奈兹里耶、粗野的南庞、破坏者加斯</font>。<br>可透过我进入城地下监狱。<br>那就拜托您了。<br><a action=\"bypass -h Quest 512_AwlUnderFoot enter\">知道了，现在就出发</a><br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_ask\">地下监狱的怪物们是何方神圣？</a></body></html>"

class PyObject:
	pass

def Reward(st) :
	if st.getState() == State.STARTED :
		if self.getRandom(9) > 5 : #No retail info about drop quantity. Guesed 1-2. 60% for 1 and 40% for 2 
			st.giveItems(DL_MARK, int(2 * Config.RATE_QUEST_DROP))
			st.playSound("ItemSound.quest_itemget")
		elif self.getRandom(9) < 6  :
			st.giveItems(DL_MARK, int(1 * Config.RATE_QUEST_DROP))
			st.playSound("ItemSound.quest_itemget") 

def checkConditions(player, new):
	party = player.getParty()
	if not party:
		player.sendPacket(SystemMessage(SystemMessageId.NOT_IN_PARTY_CANT_ENTER))
		return False
	for partyMember in party.getPartyMembers().toArray():
		if not partyMember.getLevel() >= 70:
			player.sendPacket(SystemMessage(SystemMessageId.PARTY_EXCEEDED_THE_LIMIT_CANT_ENTER))
			return False
		if not partyMember.isInsideRadius(player, 1000, False, False):
			sm = SystemMessage(SystemMessageId.C1_IS_IN_LOCATION_THAT_CANNOT_BE_ENTERED)
			sm.addCharName(partyMember)
			player.sendPacket(sm)
			return False
	return True

def teleportplayer(self, player, teleto):
	player.setInstanceId(teleto.instanceId)
	player.teleToLocation(teleto.x, teleto.y, teleto.z)
	pet = player.getPet()
	if pet != None :
		pet.setInstanceId(teleto.instanceId)
		pet.teleToLocation(teleto.x, teleto.y, teleto.z)
	return

def enterInstance(self, player, template, teleto):
	instanceId = 0
	if not checkEnter(self, player) :
		return 0
	party = player.getParty()
	#check for other instances of party members
	if party :
		for partyMember in party.getPartyMembers().toArray():
			st = partyMember.getQuestState(qn)
			if st :
				id = st.getState()
				if not id == State.STARTED :
					player.sendPacket(SystemMessage.sendString(partyMember.getName() + "队伍成员没有进行任务。"))
					return 0
			else :
				player.sendPacket(SystemMessage.sendString(partyMember.getName() + "队伍成员没有进行任务。"))
				return 0
			if partyMember.getInstanceId() != 0:
				instanceId = partyMember.getInstanceId()
				if debug: print "Rim Pailaka: found party member in instance:" + str(instanceId)
		else :
			if player.getInstanceId() != 0:
				instanceId = player.getInstanceId()
	#exising instance
	if instanceId != 0:
		if not checkConditions(player, False):
			return 0
		foundworld = False
		for worldid in self.world_ids:
			if worldid == instanceId:
				foundworld = True
		if not foundworld:
			player.sendPacket(SystemMessage.sendString("你的队员已进入其它的即时地区。"))
			return 0
		teleto.instanceId = instanceId
		teleportplayer(self, player, teleto)
		return instanceId
	#new instance
	else:
		if not checkConditions(player, True):
			return 0
		instanceId = InstanceManager.getInstance().createDynamicInstance(template)
		if not instanceId in self.world_ids:
			world = PyObject()
			world.rewarded = []
			world.instanceId = instanceId
			self.worlds[instanceId] = world
			self.world_ids.append(instanceId)
			self.currentWorld = instanceId
			print "Rim Pailaka: started. " + template + " Instance: " + str(instanceId) + " created by player: " + str(player.getName())
			self.saveGlobalQuestVar("512_NextEnter", str(System.currentTimeMillis() + 14400000))
			raidid = 1
			spawnRaid(self, world, raidid)
		#teleports player
		teleto.instanceId = instanceId
		for partyMember in party.getPartyMembers().toArray():
			st = partyMember.getQuestState(qn)
			st.set("cond", "1")
			playerName = partyMember.getName()
			teleportplayer(self, partyMember, teleto)
		return instanceId
	return instanceId

def exitInstance(self, npc) :
	if self.worlds.has_key(npc.getInstanceId()):
		world = self.worlds[npc.getInstanceId()]
		instanceObj = InstanceManager.getInstance().getInstance(self.currentWorld)
		instanceObj.setDuration(60000)
		instanceObj.removeNpcs()

def spawnRaid(self, world, raid) :
	if raid == 1 :
		spawnid = RAIDS1[Rnd.get(0, 2)]
	elif raid == 2 :
		spawnid = RAIDS2[Rnd.get(0, 3)]
	elif raid == 3 :
		spawnid = RAIDS3[Rnd.get(0, 2)]
	spawnedNpc = self.addSpawn(spawnid, 12161, -49144, -3000, 0, False, 0, False, world.instanceId)

def checkEnter(self, player) :
	entertime = self.loadGlobalQuestVar("512_NextEnter")
	if entertime.isdigit() :
		remain = long(entertime) - System.currentTimeMillis()
		if remain <= 0 :
			return True
		else :
			timeleft = remain / 60000
			player.sendPacket(SystemMessage.sendString("从现在起将会限制进入即时地区：“城堡地下监狱”。下一次的进场时间还剩" + str(timeleft) + "分钟。"))
			return False
	else :
		return True

def checkLeader(player) :
	party = player.getParty()
	if not party:
		player.sendPacket(SystemMessage(SystemMessageId.NOT_IN_PARTY_CANT_ENTER))
		return False
	elif not player.getParty().isLeader(player):
		player.sendPacket(SystemMessage(SystemMessageId.ONLY_PARTY_LEADER_CAN_ENTER))
		return False
	else :
		return True

class Quest (JQuest) :
	def __init__(self, id, name, descr):
		JQuest.__init__(self, id, name, descr)
		self.questItemIds = [DL_MARK]
		self.worlds = {}
		self.world_ids = []
		self.currentWorld = 0

	def onAdvEvent (self,event,npc, player) :
		htmltext = event
		st = player.getQuestState(qn)
		if not st : return
		if event == "start" :
			htmltext = warden_yes
			st.set("cond", "1")
			st.setState(State.STARTED)
			st.playSound("ItemSound.quest_accept")
		elif event == "quit" :
			htmltext = finish
			st.playSound("ItemSound.quest_finish")
			st.exitQuest(1)
		elif event == "continue" :
			htmltext = warden_yes
		elif event == "warden_no" :
			st.set("cond", "0")
			htmltext = warden_no
		elif event == "default" :
			htmltext = default
		elif event == "warden_yes" :
			htmltext = warden_yes
		elif event == "warden_ask" :
			htmltext = warden_ask
		elif event == "warden_ask1" :
			htmltext = warden_ask1
		elif event == "warden_ask2" :
			htmltext = warden_ask2
		elif event == "rumor" :
			htmltext = rumor
		elif event == "quest_no" :
			htmltext = quest_no
		elif event == "leave" :
			htmltext = ""
			if checkLeader(player) :
				exitInstance(self, npc)
				htmltext = "Instance deleted!"
		elif event == "status" :
			entertime = self.loadGlobalQuestVar("512_NextEnter")
			if entertime.isdigit() :
				remain = long(entertime) - System.currentTimeMillis()
				if remain <= 0 :
					htmltext = "<html><body>监狱管理员：<br>地下监狱闲置中，你现在可以进入。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_yes\">返回</a></body></html>"
				else :
					timeleft = remain / 60000
					if timeleft > 180 :
						htmltext = "<html><body>监狱管理员：<br>地下监狱现在有人挑战中。待他们离开时，然后再试一次。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_yes\">返回</a></body></html>"
					else :
						htmltext = "<html><body>监狱管理员：<br>从现在起将会限制进入即时地区：“城堡地下监狱”。下一次的进场时间还剩 <font color=\"LEVEL\">" + str(timeleft) + "</font> 分钟。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_yes\">返回</a></body></html>"
			else :
				htmltext = "<html><body>监狱管理员：<br>地下监狱闲置中，你现在可以进入。<br><a action=\"bypass -h Quest 512_AwlUnderFoot warden_yes\">返回</a></body></html>"
		elif event == "enter" :
			party = player.getParty()
			if not party:
				htmltext = noparty
			elif not player.getParty().isLeader(player):
				pln = player.getParty().getLeader().getName()
				htmltext = "<html><body>监狱管理员：<br>为了在战斗中生存，最重要的是队伍的队长如何领导自己的队伍，当然，在菲拉卡内将领导您的人，也会是队长。所以，我非常尊重队伍的领导人物。您的队长是" + str(pln) + "，去将您的队长请来这边吧。<br>(只有队长才能试图进入。)</body></html>"
			else :
				tele = PyObject()
				tele.x = 11740
				tele.y = -49148
				tele.z = -3000
				enterInstance(self, player, "RimPailakaCastle.xml", tele)
				htmltext = ""
		return htmltext

	def onTalk (self, npc, player):
		htmltext = default
		st = player.getQuestState(qn)
		if not st : return htmltext
	
		npcId = npc.getNpcId()
		id = st.getState()
		cond = st.getInt("cond")

		CASTLEID = npc.getCastle().getOwnerId()
		CLAN = player.getClan()

		if id == State.CREATED :
			if npcId in WARDEN and cond == 0 :
				if CLAN :
					CLANID = CLAN.getClanId()
				else :
					htmltext = noclan
					return htmltext
				if not CASTLEID == CLANID :
					htmltext = wrongcastle
					return htmltext
				if st :
					if player.getLevel() >= 70 :
						htmltext = warden_quest
					else :
						htmltext = nolvl
						st.exitQuest(1)
		elif id == State.STARTED :
			if npcId in WARDEN :
				if cond == 1 :
					count = st.getQuestItemsCount(DL_MARK)
					if count > 0 :
						htmltext = warden_exchange
						st.takeItems(DL_MARK, count)
						st.giveItems(KNIGHT_EPALUETTE, count * 162)
					elif count == 0 :
						htmltext = warden_yes
		return htmltext

	def onKill(self, npc, player, isPet) :
		npcId = npc.getNpcId()
		partyMembers = [player]
		party = player.getParty()
		if npc.getInstanceId() in self.worlds:
			world = self.worlds[npc.getInstanceId()]
		if npcId in RAIDS3 :
			#If is party, give item to all party member who have quest
			if party :
				partyMembers = party.getPartyMembers().toArray()
				for player in partyMembers :
					st = player.getQuestState(qn)
					if st :
						Reward(st)
			else :
				st = player.getQuestState(qn)
				if st :
					Reward(st)
			if self.worlds.has_key(npc.getInstanceId()):
				world = self.worlds[npc.getInstanceId()]
				instanceObj = InstanceManager.getInstance().getInstance(self.currentWorld)
				instanceObj.setDuration(60000)
				instanceObj.removeNpcs()
		elif npcId in RAIDS1 :
			spawnRaid(self, world, 2)
		elif npcId in RAIDS2 :
			spawnRaid(self, world, 3)
		return

	def onFirstTalk(self, npc, player) :
		st = player.getQuestState(qn)
		if not st :
			st = self.newQuestState(player)
		npcId = npc.getNpcId()
		if npcId in WARDEN :
			htmltext = "CastleWarden.htm"
		return htmltext

# Quest class and state definition
QUEST = Quest(QuestId, str(QuestId) + "_" + QuestName, QuestDesc)

for npcId in WARDEN :
	QUEST.addStartNpc(npcId)
	QUEST.addTalkId(npcId)
	QUEST.addFirstTalkId(npcId)

for mobId in RAIDS1 :
	QUEST.addKillId(mobId)
for mobId in RAIDS2 :
	QUEST.addKillId(mobId)
for mobId in RAIDS3 :
	QUEST.addKillId(mobId)